<template>
    <div class="text-size">
        <span class="textarea-tip" :class="{isActive: total > max}">{{ total }}/{{ max }}</span>
    </div>
</template>

<script>
export default {
    name: "textlength",
    props: {
        max: {
            type: Number,
            default: 0
        },
        value: {
            type: [String, Number],
            default: ""
        }
    },
    data() {
        return {
            total: 0,
        };
    },
    watch: {
        value(val) {
            if(val == ""|| val == null) {
                this.total = 0;
                this.$emit('update:length', this.total);
                return;
            }else{
                this.total = this.strlen(val) / 2;
                this.$emit('update:length', this.total);
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            if (this.value == "") {
                this.total = 0;
                this.$emit('update:length', this.total);
                return;
            }else {
                this.total = this.strlen(this.value) / 2;
                this.$emit('update:length', this.total);
            }
        })
    },
    methods: {
        strlen(str) {
            // 计算字符总长度
            var len = 0;
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                    len++;
                } else {
                    len += 2;
                }
            }
            return len;
        }
    }
};
</script>

<style scoped>
.text-size{
    height: 22px;
    line-height: 22px;
    font-size: 12px;
    color: #ADB0B8;
    margin-top: 3px;
    text-align: right;
}
.textarea-tip.isActive{
    color: red;
}
</style>
